import { failedReconnection } from "./failedReconnection";
import { reqList, stopRepeatRequest, allowRequest } from "./stopRepeatRequest";
import request from "./request";
import { useStore } from "../stores/stors";
let { instance, axios } = request;
let timeStamp = 1000;
const store = useStore();
// 添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    // console.log(config);
    // console.log(store.loginToken.token, 12345678978979);
    let token = store.loginToken.token || "";
    config.headers = {
      ...config.headers,
      "Authori-zation": "Bearer " + token,
    };
    config.retryDelay > timeStamp
      ? config.retryDelay
      : (config.retryDelay = config.retryDelay + timeStamp);
    // 在发送请求之前做些什么
    let cancel;
    // 设置cancelToken对象
    config.cancelToken = new axios.CancelToken(function (c) {
      cancel = c;
    });
    // 阻止重复请求。当上个请求未完成时，相同的请求不会进行
    stopRepeatRequest(reqList, config.url, cancel, `${config.url} 请求被中断`);
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    setTimeout(() => {
      allowRequest(reqList, response.config.url);
    }, timeStamp);
    let { data } = response;
    return data;
  },
  (error) => {
    if (axios.isCancel(error)) {
      // console.log(error.message);
      return Promise.reject(error.message);
    }
    // 增加延迟，相同请求不得在短时间内重复发送
    setTimeout(() => {
      allowRequest(reqList, error.config.url);
    }, timeStamp);
    return failedReconnection(error, instance);
  }
);

export default instance;
